package com.suncm3kw.chatgpt.controller;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suncm3kw.chatgpt.entity.SseEmitterUTF8;
import com.suncm3kw.chatgpt.service.AiChatDataService;
import com.suncm3kw.chatgpt.vo.RequestChatVo;

@RestController
@RequestMapping("/chatGpt")
public class ChatGptController {

	@Autowired
	@Qualifier("chatDataService")
	AiChatDataService aiChatDataService;

	@Value("${chatGpt.httpHead}")
	private String apiChatHead;

	@CrossOrigin
	@ResponseBody
	@PostMapping("/completions")
	public SseEmitter requestFastGptPostOrigin(@RequestBody RequestChatVo vo) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("chatId", vo.getChatId());
		jsonObject.put("token", vo.getToken());
		jsonObject.put("stream",vo.isStream());
		jsonObject.put("detail", vo.isDetail());
		jsonObject.put("model", vo.getModel());
		JSONArray jsonArray = new JSONArray();

		JSONObject jsonMessage = new JSONObject();
		jsonMessage.put("content", vo.getContent());
		jsonMessage.put("role", "user");
		jsonArray.add(jsonMessage);
		jsonObject.put("messages", jsonArray);

		final SseEmitterUTF8 emitter = aiChatDataService.getConn(vo.getToken());
		emitter.setDone(false);
		CompletableFuture.runAsync(() -> {
			try {
				aiChatDataService.sentSseMessageOrigin(emitter, apiChatHead, jsonObject.toJSONString(),vo.getChatId(),true);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		});
		return emitter;
	}

}
